package com.qf.controller;

import com.qf.dto.R;
import com.qf.events.UserLoginEvent;
import com.qf.pojo.User;
import com.qf.service.UserService;
import com.qf.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/users")
public class UserController {

    private UserService userService;

    private ApplicationContext context;

    @Autowired
    public void setContext(ApplicationContext context) {
        this.context = context;
    }

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/registry")
    public R registry(@RequestBody User user) {
        //insert语句只有两种结果,一个是抛出异常,一个是插入成功多少条
        //update有条件,所以他的结果有三种,一种是抛出异常,一种是更新成功数据,一种是更新成功0条
        userService.addUser(user);
        return R.setOK();
    }

    @PostMapping("/login")
    public R login(String username, String password, HttpSession session){
        User user = userService.login(username, password);
        session.setAttribute("user",user);
        context.publishEvent(new UserLoginEvent());
        return R.setOK(user.getUsername());

    }

}
